from PyQt5.QtWidgets import QWidget, QMessageBox, QShortcut
from PyQt5.QtGui import \
    (QPainter, QFont,
     QPen, QTouchEvent, QMouseEvent, QKeySequence)
from PyQt5.QtCore import QRect, Qt, QEvent

square_w = 80
tip = "请使用一根手指触摸"


class TpDrawLineWidget(QWidget):
    rectangles = []
    points = []
    coordinate = "(0, 0)"

    def __init__(self, parent=None):
        super().__init__(parent)
        # self.rect = QRect(10, 15, 90, 60)
        self.initUI()
        ## 加载配置文件
        import utils.configHandlers
        self.myConfig = utils.configHandlers.configHandler.configs
        print('TpDrawLineWindow get config Version', self.myConfig.version)
        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               F11')
        self.WindowSizeFun()

    def initUI(self):
        print('touch widget')
        # self.setGeometry(0, 0, 100, 100)
        # self.setWindowTitle('Colours')
        self.setAttribute(Qt.WA_AcceptTouchEvents)
        self.setStyleSheet('''QWidget{background-color:rgb(255, 255, 255);}''')
        # self.setAutoFillBackground(True)

        # self.show()
    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'
    def paintEvent(self, e):
        # print("paint")
        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        self.drawPoints(qp)
        self.drawTip(qp)
        self.drawCoordinate(qp)
        qp.end()

    def handleMove(self, pos):
        self.points.append(pos)
        self.coordinate = f"  ({pos.x()}, {pos.y()})  "
        indexes = []
        for i in range(len(self.rectangles)):
            r = self.rectangles[i]
            # print('rect: ' + str(r) + ' pos:' + str(pos))
            if r[0]:
                pass
            if r[1].contains(pos):
                # print('True' + str(r) + ' pos:' + str(pos))
                indexes.append(i)
            # else:
            # print('False' + str(r) + ' pos:' + str(pos))
        # print('indexes len: ' + str(len(indexes)))
        if len(indexes) >= 0:
            for index in indexes:
                self.rectangles[index] = (True, self.rectangles[index][1])
        self.update()

    def handleMouseEvent(self, e: QMouseEvent):
        # print('Mouse event')
        if e.type() == QEvent.MouseMove:
            pos = e.pos()
            self.handleMove(pos)
        elif e.type() == QEvent.MouseButtonRelease:
            all_filled = True
            for r in self.rectangles:
                if not r[0]:
                    all_filled = False
                    break
            if all_filled:
                self.myConfig.passTestItems.add('TpDrawLine')
                # info = QMessageBox.information(self, "Message", "划线结束，TP测试通过",
                #                                QMessageBox.Ok)
                # if info == QMessageBox.Ok:
                #     self.adjustRectangles(self)
                #     self.update()

    def handleTouchEvent(self, e: QTouchEvent):
        print('Touch event')
        if e.type() == QEvent.TouchBegin:
            touch_points = e.touchPoints()
            touch_len = len(touch_points)
            print(f'touch count: ' + str(touch_len))
            if touch_len > 1:
                reply = QMessageBox.question(self, 'Message',
                                             "超过一根手指触摸屏幕，确认退出触摸测试？",
                                             QMessageBox.Yes | QMessageBox.No | QMessageBox.Retry,
                                             QMessageBox.No)
                if reply == QMessageBox.Yes:
                    print('yes')
                elif reply == QMessageBox.No:
                    print('no')
                    pass
                else:
                    self.adjustRectangles(self)
                    self.update()
                    print('retry')
        if e.type() == QEvent.TouchUpdate:
            touch_points = e.touchPoints()
            self.handleMove(touch_points[0].pos())
        if e.type() == QEvent.TouchEnd:
            all_filled = True
            for r in self.rectangles:
                if not r[0]:
                    all_filled = False
                    break
            if all_filled:
                info = QMessageBox.information(self, "Message", "划线结束，TP测试通过",
                                               QMessageBox.Ok)

            pass

    def adjustRectangles(self, e):
        self.points.clear()
        self.rectangles.clear()
        screen_w = e.size().width()
        screen_h = e.size().height()
        if screen_w == 0 or screen_h == 0:
            return
        # print('w:' + str(screen_w) + ", h:" + str(screen_h))
        n = int(screen_w / square_w) - 2
        w = int(screen_w / (n + 2))
        h = int((2 * screen_h) / (n + 5))
        left = 0
        top = 0

        horizontal_limit = int(screen_w - w * 3 / 2)
        horizontal_delta = w
        vertical_delta = h
        # first row
        while left < horizontal_limit:
            self.rectangles.append((False, QRect(left, top, w, h)))
            left += horizontal_delta
        # the last rectangle in the first row
        last_rect_w = screen_w - left
        last_rect_left = left
        self.rectangles.append((False, QRect(last_rect_left, top, last_rect_w, h)))
        # first column
        vertical_limit = int(screen_h - h * 3 / 2)
        left = 0
        top = vertical_delta
        while top < vertical_limit:
            self.rectangles.append((False, QRect(left, top, w, h)))
            top += vertical_delta
        # last column
        last_rect_top = top
        last_rect_h = screen_h - top
        top = vertical_delta
        while top < vertical_limit:
            self.rectangles.append((False, QRect(last_rect_left, top, last_rect_w, h)))
            top += vertical_delta
        # last row
        left = 0
        while left < horizontal_limit:
            self.rectangles.append((False, QRect(left, last_rect_top, w, last_rect_h)))
            left += horizontal_delta
        # last square on the right bottom conner
        self.rectangles.append((False, QRect(left, last_rect_top, last_rect_w, last_rect_h)))
        # diagonal rectangle
        left = horizontal_delta
        top = vertical_delta
        # first rectangle
        self.rectangles.append((False, QRect(left, top, w, h)))
        # middle rectangle
        left = int(horizontal_delta * 2)
        dia_top = vertical_delta + int(((screen_h - h - last_rect_h) - (n + 1) * h / 2) / 2 + h / 2)
        top = dia_top
        while left < horizontal_limit - vertical_delta:
            self.rectangles.append((False, QRect(left, top, w, h)))
            left += horizontal_delta
            top += int(h / 2)
        # last rectangle
        last_dia_rect_h = screen_h - h - last_rect_h
        self.rectangles.append((False, QRect(left, last_dia_rect_h, w, h)))
        # another side
        # first rectangle
        left = screen_w - w - last_rect_w
        top = vertical_delta
        self.rectangles.append((False, QRect(left, top, w, h)))
        # middle rectangle
        left -= horizontal_delta
        top = dia_top
        while left > w:
            self.rectangles.append((False, QRect(left, top, w, h)))
            left -= horizontal_delta
            top += int(h / 2)
        # last rectangle
        left = horizontal_delta
        self.rectangles.append((False, QRect(left, last_dia_rect_h, w, h)))
        # for r in self.rectangles:
        #     print(str(r))

    def resizeEvent(self, e) -> None:
        self.adjustRectangles(e)

    def event(self, e: QEvent) -> bool:
        if isinstance(e, QMouseEvent):
            self.handleMouseEvent(e)
        elif isinstance(e, QTouchEvent):
            self.handleTouchEvent(e)

        return QWidget.event(self, e)

    def drawTip(self, qp):
        qp.setPen(Qt.red)
        qp.setFont(QFont('SimSun', 25))
        qp.drawText(QRect(self.rect().left(), self.rect().top(),
                          self.rect().width(), self.rect().height() / 2),
                    Qt.AlignCenter, tip)

    def drawCoordinate(self, qp):
        qp.setPen(Qt.black)
        qp.setFont(QFont('SimSun', 20))
        qp.drawText(QRect(self.rect().left(), self.rect().top() + self.rect().height() / 2,
                          self.rect().width(), self.rect().height() / 2),
                    Qt.AlignCenter, self.coordinate)

    def drawPoints(self, qp):
        qp.setPen(QPen(Qt.black, 3))
        for p in self.points:
            qp.drawPoints(p)

    def drawRectangles(self, qp):
        qp.setPen(QPen(Qt.black, 1, Qt.SolidLine))
        # print('rect count: ' + str(len(self.rectangles)))
        for r in self.rectangles:
            if r[0]:
                qp.setBrush(Qt.green)
            else:
                qp.setBrush(Qt.white)
            # qp.setBrush(QColor(255, 80, 0, 160))
            qp.drawRect(r[1])
        # col = QColor(0, 0, 0)
        # col.setNamedColor('#d4d4d4')
        # qp.setPen(QPen(Qt.black, 1, Qt.SolidLine))
        #
        # qp.setBrush(QColor(200, 0, 0))
        # qp.drawRect(self.rect)
        #
        # # if self.rect.contains(50, 50):
        #     # print("contain")
        #
        # qp.setBrush(QColor(255, 80, 0, 160))
        # qp.drawRect(130, 15, 90, 60)
        #
        # qp.setBrush(QColor(25, 0, 90, 200))
        # qp.drawRect(250, 15, 90, 60)
